package com.km.wskj.itmonitor.pager.login;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.zxl.zxlapplibrary.control.LoginControl;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.ClearEditText;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.toolsfinal.StringUtils;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;

/**
 * @author by Xianling.Zhou on 2017/2/7.
 */

public class LoginActivity extends LActivity {
    private static final String TAG = "LoginActivity";

    //ui
    @BindView(R.id.et_loginname)
    ClearEditText et_loginname;
    @BindView(R.id.et_loginpwd)
    ClearEditText et_loginpwd;
    @BindView(R.id.tool_bar_back)
    ImageView mBack;
    @BindView(R.id.tool_bar_title)
    TextView mTitle;

    private String password = "123456";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        //沉浸shi
        StatusBarCompat.compat(this, getResources().getColor(R.color.colorWs_blue));
        mBack.setVisibility(View.VISIBLE);
        mTitle.setText("登陆");

        et_loginpwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    onBtnLogin(null);
                }
                return false;
            }
        });


        //是否配置了记住密码
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isremmeber = sp.getBoolean(Constant.SET_PWD_REMEMBER, true);

        //显示记录的登录名
        String loginname = LoginControl.readLoginName(this);
        if (!StringUtils.isEmpty(loginname)) {
            et_loginname.setText(loginname);
            if (isremmeber) {
                String loginpwd = LoginControl.readPasswordForName(this, loginname);
                et_loginpwd.setText(loginpwd);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(Constant.ResultExit);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick(R.id.btn_login)
    public void onBtnLogin(View v) {
        final String loginname = et_loginname.getText().toString();
        final String password = et_loginpwd.getText().toString();

        if (StringUtils.isEmpty(loginname)) {
            et_loginname.setShakeAnimation();
            normalToasty("用户名不能为空");
            return;
        }
        if (StringUtils.isEmpty(password)) {
            et_loginpwd.setShakeAnimation();
            normalToasty("密码不能为空");
            return;
        }

        IMLogin(loginname);
        final ProgressDialog progressDialog = ProgressDialog.show(this, "请稍后", "验证中...", true);
        pdc.login(HTTP_TASK_TAG, loginname, password, pdc.new LoginCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                progressDialog.dismiss();
                LogUtils.e(TAG, e);
                errorToasty(e.getMessage(), true);
            }

            @Override
            public void onResponse(Object o, int i) {
                successToasty("登陆成功", true);
                progressDialog.dismiss();
                LoginControl.saveLoginName(context, loginname);
                //如果需要记住密码
                LoginControl.savePasswordForName(context, loginname, password);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
                    }

                }, 500);

            }
        });
    }

    //-------------------------环信--------------------------
    private void IMRegist(final String username, final String password) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(username, password);
                    IMLogin(username);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    LogUtils.e("注册失败" + e.toString());
                }
            }
        }).start();
    }

    private void IMLogin(final String username) {

        EMClient.getInstance().login(username, password, new EMCallBack() {
            @Override
            public void onSuccess() {
                LogUtils.e("环信登陆成功！！！！");
                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
            }

            @Override
            public void onError(int i, String s) {
                LogUtils.e(i + "," + s);
                IMRegist(username, password);
            }

            @Override
            public void onProgress(int i, String s) {
                LogUtils.e(i + "," + s);
            }
        });
    }


    @OnClick({R.id.tool_bar_back, R.id.tv_reg})
    public void back(View v) {
        switch (v.getId()) {
            case R.id.tv_reg:
                openIntent(RegSendCodeActivity.class, true);
                break;
            case R.id.tool_bar_back:
                finish();
                break;
        }

    }


}
